package cn.zwx.common.canal.listener;
import cn.zwx.common.canal.bo.CovertMessageBO;
import cn.zwx.common.canal.enums.BuisType;
import cn.zwx.common.canal.event.UpdateAbstractCanalEvent;
import cn.zwx.common.canal.handler.CovertMessageHandler;
import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * 修改事件监听
 */
@Component
public class UpdateCanalListener extends AbstractCanalListener<UpdateAbstractCanalEvent> {

    private final Logger logger = LoggerFactory.getLogger(UpdateCanalListener.class);

    @Autowired
    private CovertMessageHandler covertMessageHandler;

    @Override
    protected void doChange(String database, String tableName, CanalEntry.RowData rowData,String instanceName,String topic) {
        logger.info("监听到修改事件:数据库名称{},表名称:{},实例:{},topic:{}",database,tableName,instanceName,topic);
        // 获取修改之前的数据
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        // 解析修改之前数据之后的内容
        Map<String, String> beforeColumnsMap = this.getColumnsList(beforeColumnsList);
        logger.info("修改之前数据:{}", JSON.toJSONString(beforeColumnsMap));
        // 获取修改之后的数据
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        // 转换发送消息类
        CovertMessageBO messageBO = new CovertMessageBO();
        messageBO.setDatabase(database);
        messageBO.setBusiType(BuisType.UPDATE.getCode());
        messageBO.setTableName(tableName);
        messageBO.setAfterColumnsList(afterColumnsList);
        messageBO.setBeforeColumnsList(beforeColumnsList);
        Map<String, Object> messageMap = covertMessageHandler.covertMessageDTO(messageBO);
        // 发送MQ
        logger.info(String.format("{%s},发送mq请求参数:",BuisType.UPDATE.getMsg())+ JSON.toJSONString(messageMap));
    }

    /**
     * @description 获取列的参数
     **/
    private Map<String, String> getColumnsList(List<CanalEntry.Column> beforeColumnsList) {
        Map<String, String> columnMap = CollectionUtils.newHashMap(16);
        for (CanalEntry.Column column : beforeColumnsList) {
            String columnName = column.getName();
            String columnValue = column.getValue();
            columnMap.put(covertMessageHandler.underline2Camel(columnName), columnValue);
        }
        return columnMap;
    }
}
